<?php

namespace app\admin\controller;

class City extends Base {
    public function _initialize() {
        parent::_initialize();
    }

    /**
     * 首页
     * @return mixed
     */
    public function index(){
        $parentId = input('get.parent_id', 0, 'intval');
        $cities = $this->modelObj->getCities($parentId);
        return $this->fetch('',[
            'cities'=>$cities,
            'count'=>$this->modelObj->countCity(),
        ]);
    }

    /**
     * 添加页面
     * @return mixed
     */
    public function add(){
        $firstCity = $this->modelObj->getNormalFirstCity();
        return $this->fetch('', [
            'firstCity'=>$firstCity,
        ]);
    }

    /**
     * 修改页面
     * @param int $id 修改的目标id
     * @return mixed
     */
    public function edit($id = 0){
        if(intval($id) < 1){
            $this->error('参数不合法！');
        }
        $city = $this->modelObj->get($id);
        $firstCity = $this->modelObj->getNormalFirstCity();
        return $this->fetch('', [
            'firstCity'=>$firstCity,
            'city'=>$city,
        ]);
    }

    /**
     * 将分类信息写入数据库的函数
     */
    public function save(){
        //严格校验是否为POST
        if(!request()->isPost()){
            $this->error('请求失败');
        }
        $data = input('post.'); //获取“添加分类”表单数据
        $validate = validate('City');//表单验证器
        if(!$validate->scene("add")->check($data)){
            $this->error($validate->getError());
        }
        if(!empty($data['id'])){
            return $this->update($data);
        }
        //将$data 提交model层
        $res = $this->modelObj->add($data);
        if($res){
            $this->success("添加成功", url('successView'));
        }else{
            $this->error("添加失败！");
        }
    }

}